from PyQt6.QtCore import QTimer

import contents
from client import Client
from status import status
from ui import ui


class Game(QTimer):
    def __init__(self):
        super().__init__(ui)
        self.msg_send = None
        self.msg_recv = None
        self.start(10)
        self.client = Client()
        self.callback = None
        self.log_file = open("log.txt", "w", encoding="utf-8")

    def timerEvent(self, a0) -> None:
        if self.callback is not None:
            if self.callback():
                self.callback = None
                self.resume()
        elif self.msg_send:
            self.client.send(self.msg_send)
            self.msg_send = None
            self.resume()
        else:
            if self.msg_recv:
                print(self.msg_recv)
                raise RuntimeError("error! msg_recv not handled!")
            msg = self.client.recv()
            if msg:
                self.msg_recv = msg
                self.resume()

    def log(self, msg: str):
        self.log_file.write(msg)
        self.log_file.write("\n")
        self.log_file.flush()
        ui.log(msg)

    def run(self):
        status.event.create_event("main_window", False).set_content(contents.main_window)
        self.loop()

    def trigger(self, name):
        event = status.event.create_event("arrange_trigger", triggering=0)
        event.set_content(contents.arrange_trigger)
        event.prompt = name

    def loop(self):
        event = status.event

        if status.paused:
            return

        if status.event.child:
            status.event = status.event.child
        elif event.triggering == 1:
            self.trigger(event.name + "_before")
            event.triggering += 1
        elif event.triggering == 3:
            self.trigger(event.name + "_after")
            event.triggering += 1
        elif event.triggering == 4:
            status.event.parent.child_result = status.event.result
            status.event = status.event.parent
            status.event.child = None
        else:
            event.content(event, status, self, ui)
            event.forward()

        self.loop()

    def pause(self):
        status.paused = True

    def resume(self):
        if status.paused:
            status.paused = False
            self.loop()

    def __del__(self):
        print(1)
        self.log_file.close()


game = Game()
